package Demo2_5;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User：Lenovo
 * Date:2025-02-05
 * Time:17:49
 */
// 定义二叉树节点类
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

public class BalancedBinaryTree {
    // 判断二叉树是否为平衡二叉树的主方法
    public boolean isBalanced(TreeNode root) {
        return getHeight(root) != -1;
    }

    // 辅助方法，用于计算树的高度，如果树不平衡则返回 -1
    private int getHeight(TreeNode node) {
        if (node == null) {
            return 0;
        }
        // 递归计算左子树的高度
        int leftHeight = getHeight(node.left);
        if (leftHeight == -1) {
            return -1;
        }
        // 递归计算右子树的高度
        int rightHeight = getHeight(node.right);
        if (rightHeight == -1) {
            return -1;
        }
        // 判断当前节点的左右子树高度差是否超过 1
        if (Math.abs(leftHeight - rightHeight) > 1) {
            return -1;
        }
        // 返回当前节点的高度
        return Math.max(leftHeight, rightHeight) + 1;
    }

    public static void main(String[] args) {
        // 构建一个示例二叉树
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);

        BalancedBinaryTree solution = new BalancedBinaryTree();
        boolean result = solution.isBalanced(root);
        System.out.println("该二叉树是否为平衡二叉树: " + result);
    }
}
